<template>
  <div class="workorder-create">
    <a-card :bordered="false">
      <template #title>
        <span>创建工单</span>
      </template>

      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        layout="vertical"
        @finish="handleSubmit"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="工单标题" name="title" required>
              <a-input
                v-model:value="form.title"
                placeholder="请输入工单标题"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="维修类别" name="categoryId" required>
              <a-select
                v-model:value="form.categoryId"
                placeholder="请选择维修类别"
                :loading="categoriesLoading"
              >
                <a-select-option
                  v-for="category in categories"
                  :key="category.id"
                  :value="category.id"
                >
                  {{ category.categoryName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="故障位置" name="location" required>
              <a-input
                v-model:value="form.location"
                placeholder="请输入具体位置，如：宿舍楼栋号-房间号"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系电话" name="contactPhone" required>
              <a-input
                v-model:value="form.contactPhone"
                placeholder="请输入联系电话"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="问题描述" name="description" required>
          <a-textarea
            v-model:value="form.description"
            placeholder="请详细描述遇到的问题"
            :rows="4"
          />
        </a-form-item>

        <a-form-item label="故障位置" name="location" required>
          <a-input
            v-model:value="form.location"
            placeholder="请输入具体的故障位置（如：宿舍号、楼层等）"
          />
        </a-form-item>

        <a-form-item label="上传图片" name="images">
          <a-upload
            v-model:file-list="fileList"
            list-type="picture-card"
            :before-upload="beforeUpload"
            @preview="handlePreview"
            @remove="handleRemove"
            :multiple="true"
            :max-count="5"
          >
            <div v-if="fileList.length < 5">
              <plus-outlined />
              <div style="margin-top: 8px">上传图片</div>
            </div>
          </a-upload>
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button
              type="primary"
              html-type="submit"
              :loading="loading"
              size="large"
            >
              <SaveOutlined />
              提交工单
            </a-button>
            <a-button
              @click="handleReset"
              size="large"
            >
              <ReloadOutlined />
              重置
            </a-button>
            <a-button
              @click="router.back()"
              size="large"
            >
              返回
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 图片预览弹窗 -->
    <a-modal
      v-model:open="previewVisible"
      :title="previewTitle"
      :footer="null"
    >
      <img
        alt="preview"
        style="width: 100%"
        :src="previewImage"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message, type UploadFile } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { createWorkOrder } from '@/api/workorder'
import { getActiveCategories } from '@/api/category'

import type { WorkOrderCreateRequest, WorkOrderAddRequest, RepairCategory } from '@/types'
import type { FormInstance, Rule } from 'ant-design-vue/es/form'
import {
  PlusOutlined,
  SaveOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const appStore = useAppStore()

const loading = ref(false)
const categoriesLoading = ref(false)
const categories = ref<RepairCategory[]>([])

// 表单
const formRef = ref<FormInstance>()
const form = reactive<WorkOrderCreateRequest>({
  title: '',
  description: '',
  categoryId: undefined,
  location: '',
  contactPhone: '',
  images: []
})

// 文件上传
const fileList = ref<UploadFile[]>([])
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')

// 表单验证规则
const rules: Record<string, Rule[]> = {
  title: [
    { required: true, message: '请输入工单标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度为5-100个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入问题描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度为10-500个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择维修类别', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入故障位置', trigger: 'blur' },
    { min: 2, max: 100, message: '位置描述长度为2-100个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 获取维修类别列表
const fetchCategories = async () => {
  try {
    categoriesLoading.value = true
    const response = await getActiveCategories()
    if (response.code === 0) {
      categories.value = response.data || []
    }
  } catch (error) {
    console.error('获取维修类别失败:', error)
  } finally {
    categoriesLoading.value = false
  }
}

// 文件上传前处理
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }

  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    message.error('图片大小不能超过5MB!')
    return false
  }

  return false // 阻止自动上传，手动处理
}

// 图片预览
const handlePreview = (file: UploadFile) => {
  previewImage.value = file.url || file.thumbUrl || ''
  previewVisible.value = true
  previewTitle.value = file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1)
}

// 移除图片
const handleRemove = (file: UploadFile) => {
  const index = fileList.value.indexOf(file)
  const newFileList = fileList.value.slice()
  newFileList.splice(index, 1)
  fileList.value = newFileList
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    // 处理图片上传
    const imageUrls: string[] = []
    for (const file of fileList.value) {
      if (file.originFileObj) {
        // 这里应该调用图片上传接口
        // const uploadResponse = await uploadImage(file.originFileObj)
        // imageUrls.push(uploadResponse.data.url)

        // 临时处理：使用本地URL
        imageUrls.push(URL.createObjectURL(file.originFileObj))
      }
    }

    const submitData: WorkOrderAddRequest = {
      categoryId: form.categoryId!,
      title: form.title,
      description: form.description,
      location: form.location,
      imagesUrl: imageUrls
    }

    const response = await createWorkOrder(submitData)
    if (response.code === 0) {
      message.success('工单创建成功')
      router.push('/workorder/list')
    }
  } catch (error) {
    console.error('创建工单失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  fileList.value = []
  form.title = ''
  form.description = ''
  form.categoryId = undefined
  form.location = ''
  form.contactPhone = userStore.userInfo?.phoneNumber || ''
  form.images = []
}

onMounted(() => {
  // 检查权限
  if (!userStore.isStudent && !userStore.isAdmin) {
    message.error('只有学生和管理员可以创建工单')
    router.back()
    return
  }

  // 设置面包屑
  appStore.setBreadcrumbs([
    { title: '首页', path: '/dashboard' },
    { title: '工单管理', path: '/workorder/list' },
    { title: '创建工单' }
  ])

  // 初始化数据
  fetchCategories()

  // 预填联系电话
  if (userStore.userInfo?.phoneNumber) {
    form.contactPhone = userStore.userInfo.phoneNumber
  }
})
</script>

<style scoped>
.workorder-create {
  padding: 0;
}

:deep(.ant-upload-select-picture-card) {
  width: 104px;
  height: 104px;
}

:deep(.ant-upload-list-picture-card .ant-upload-list-item) {
  width: 104px;
  height: 104px;
}
</style>
